package com.dayang.framework.biz.context.interceptor;

import com.dayang.framework.biz.context.holder.LoginUserContextHolder;
import com.dayang.framework.common.constants.GlobalConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.Objects;

/**
 * @author: dayang
 * @since: 2024/8/7
 * @description: Feign 请求拦截器
 */


@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 设置 traceId
        requestTemplate.header(GlobalConstants.TRACE_ID, MDC.get(GlobalConstants.TRACE_ID));
        // 获取当前上下文中的用户 ID
        Long userId = LoginUserContextHolder.getUserId();
        // 若不为空，则添加到请求头中
        if (Objects.nonNull(userId)) {
            requestTemplate.header(GlobalConstants.USER_ID, String.valueOf(userId));
        }

    }
}
